package com.seafood.controller;

import com.seafood.common.Result;
import com.seafood.dto.FileUploadDTO;
import com.seafood.dto.FileUploadRequestDTO;
import com.seafood.dto.FileUploadResponseDTO;
import com.seafood.service.FileUploadService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/api/files")
@RequiredArgsConstructor
public class FileUploadController {
    
    private final FileUploadService fileUploadService;
    
    // 上传单个文件
    @PostMapping("/upload")
    public ResponseEntity<Result<FileUploadResponseDTO>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @Valid @ModelAttribute FileUploadRequestDTO requestDTO,
            Authentication authentication) {
        
        Long uploaderId = getUserId(authentication);
        String uploaderName = authentication.getName();
        
        FileUploadResponseDTO response = fileUploadService.uploadFile(file, requestDTO, uploaderId, uploaderName);
        return ResponseEntity.ok(Result.success("文件上传成功", response));
    }
    
    // 批量上传文件
    @PostMapping("/upload-batch")
    public ResponseEntity<Result<List<FileUploadResponseDTO>>> uploadFiles(
            @RequestParam("files") List<MultipartFile> files,
            @Valid @ModelAttribute FileUploadRequestDTO requestDTO,
            Authentication authentication) {
        
        Long uploaderId = getUserId(authentication);
        String uploaderName = authentication.getName();
        
        List<FileUploadResponseDTO> responses = fileUploadService.uploadFiles(files, requestDTO, uploaderId, uploaderName);
        return ResponseEntity.ok(Result.success("文件批量上传成功", responses));
    }
    
    // 根据ID获取文件信息
    @GetMapping("/{id}")
    public ResponseEntity<Result<FileUploadDTO>> getFileById(@PathVariable Long id) {
        FileUploadDTO file = fileUploadService.getFileById(id);
        return ResponseEntity.ok(Result.success(file));
    }
    
    // 根据业务类型和业务ID获取文件列表
    @GetMapping("/business/{businessType}")
    public ResponseEntity<Result<List<FileUploadDTO>>> getFilesByBusiness(
            @PathVariable String businessType,
            @RequestParam(required = false) Long businessId) {
        
        List<FileUploadDTO> files = fileUploadService.getFilesByBusiness(businessType, businessId);
        return ResponseEntity.ok(Result.success(files));
    }
    
    // 获取我的文件列表（分页）
    @GetMapping("/my-files")
    public ResponseEntity<Result<Page<FileUploadDTO>>> getMyFiles(
            @PageableDefault(size = 20) Pageable pageable,
            Authentication authentication) {
        
        Long uploaderId = getUserId(authentication);
        Page<FileUploadDTO> files = fileUploadService.getFilesByUploader(uploaderId, pageable);
        return ResponseEntity.ok(Result.success(files));
    }
    
    // 根据文件类型获取文件列表（分页）
    @GetMapping("/type/{fileType}")
    public ResponseEntity<Result<Page<FileUploadDTO>>> getFilesByType(
            @PathVariable String fileType,
            @PageableDefault(size = 20) Pageable pageable) {
        
        Page<FileUploadDTO> files = fileUploadService.getFilesByType(fileType, pageable);
        return ResponseEntity.ok(Result.success(files));
    }
    
    // 获取公开文件列表（分页）
    @GetMapping("/public")
    public ResponseEntity<Result<Page<FileUploadDTO>>> getPublicFiles(
            @PageableDefault(size = 20) Pageable pageable) {
        
        Page<FileUploadDTO> files = fileUploadService.getPublicFiles(pageable);
        return ResponseEntity.ok(Result.success(files));
    }
    
    // 搜索文件
    @GetMapping("/search")
    public ResponseEntity<Result<Page<FileUploadDTO>>> searchFiles(
            @RequestParam String keyword,
            @PageableDefault(size = 20) Pageable pageable) {
        
        Page<FileUploadDTO> files = fileUploadService.searchFiles(keyword, pageable);
        return ResponseEntity.ok(Result.success(files));
    }
    
    // 获取热门下载文件
    @GetMapping("/popular")
    public ResponseEntity<Result<Page<FileUploadDTO>>> getPopularFiles(
            @PageableDefault(size = 20) Pageable pageable) {
        
        Page<FileUploadDTO> files = fileUploadService.getPopularFiles(pageable);
        return ResponseEntity.ok(Result.success(files));
    }
    
    // 获取最近上传的文件
    @GetMapping("/recent")
    public ResponseEntity<Result<Page<FileUploadDTO>>> getRecentFiles(
            @PageableDefault(size = 20) Pageable pageable) {
        
        Page<FileUploadDTO> files = fileUploadService.getRecentFiles(pageable);
        return ResponseEntity.ok(Result.success(files));
    }
    
    // 下载文件
    @GetMapping("/download/{id}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable Long id) {
        FileUploadDTO fileInfo = fileUploadService.getFileById(id);
        byte[] fileContent = fileUploadService.downloadFile(id);
        
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, 
                       "attachment; filename=\"" + fileInfo.getOriginalFilename() + "\"")
                .contentType(MediaType.parseMediaType(fileInfo.getContentType()))
                .body(fileContent);
    }
    
    // 删除文件（软删除）
    @DeleteMapping("/{id}")
    public ResponseEntity<Result<String>> deleteFile(
            @PathVariable Long id,
            Authentication authentication) {
        
        Long operatorId = getUserId(authentication);
        fileUploadService.deleteFile(id, operatorId);
        return ResponseEntity.ok(Result.success("文件删除成功"));
    }
    
    // 批量删除文件
    @DeleteMapping("/batch")
    public ResponseEntity<Result<String>> deleteFiles(
            @RequestBody List<Long> fileIds,
            Authentication authentication) {
        
        Long operatorId = getUserId(authentication);
        fileUploadService.deleteFiles(fileIds, operatorId);
        return ResponseEntity.ok(Result.success("文件批量删除成功"));
    }
    
    // 物理删除文件（管理员功能）
    @DeleteMapping("/physical/{id}")
    public ResponseEntity<Result<String>> physicalDeleteFile(@PathVariable Long id) {
        fileUploadService.physicalDeleteFile(id);
        return ResponseEntity.ok(Result.success("文件物理删除成功"));
    }
    
    // 更新文件信息
    @PutMapping("/{id}")
    public ResponseEntity<Result<FileUploadDTO>> updateFileInfo(
            @PathVariable Long id,
            @RequestParam(required = false) String description,
            @RequestParam(required = false) String tags,
            @RequestParam(required = false) Boolean isPublic) {
        
        FileUploadDTO updated = fileUploadService.updateFileInfo(id, description, tags, isPublic);
        return ResponseEntity.ok(Result.success("文件信息更新成功", updated));
    }
    
    // 生成缩略图
    @PostMapping("/{id}/thumbnail")
    public ResponseEntity<Result<String>> generateThumbnail(
            @PathVariable Long id,
            @RequestParam(defaultValue = "200") Integer width,
            @RequestParam(defaultValue = "200") Integer height) {
        
        String thumbnailUrl = fileUploadService.generateThumbnail(id, width, height);
        return ResponseEntity.ok(Result.success("缩略图生成成功", thumbnailUrl));
    }
    
    // 检查文件是否存在（根据MD5去重）
    @GetMapping("/check-exists")
    public ResponseEntity<Result<FileUploadResponseDTO>> checkFileExists(@RequestParam String md5) {
        FileUploadResponseDTO existingFile = fileUploadService.checkFileExists(md5);
        
        if (existingFile != null) {
            return ResponseEntity.ok(Result.success("文件已存在", existingFile));
        } else {
            return ResponseEntity.ok(Result.success("文件不存在", null));
        }
    }
    
    // 获取文件统计信息（管理员功能）
    @GetMapping("/statistics")
    public ResponseEntity<Result<Map<String, Object>>> getFileStatistics() {
        Map<String, Object> statistics = fileUploadService.getFileStatistics();
        return ResponseEntity.ok(Result.success(statistics));
    }
    
    // 获取用户文件统计
    @GetMapping("/my-statistics")
    public ResponseEntity<Result<Map<String, Object>>> getMyFileStatistics(Authentication authentication) {
        Long uploaderId = getUserId(authentication);
        Map<String, Object> statistics = fileUploadService.getUserFileStatistics(uploaderId);
        return ResponseEntity.ok(Result.success(statistics));
    }
    
    // 清理孤立文件（管理员功能）
    @PostMapping("/cleanup-orphan")
    public ResponseEntity<Result<String>> cleanupOrphanFiles() {
        fileUploadService.cleanupOrphanFiles();
        return ResponseEntity.ok(Result.success("孤立文件清理完成"));
    }
    
    /**
     * 从认证信息中获取用户ID
     */
    private Long getUserId(Authentication authentication) {
        // 这里需要根据实际的用户认证实现来获取用户ID
        // 示例实现：假设用户ID存储在认证主体中
        return 1L; // 临时返回固定值，实际应该从认证信息中获取
    }
}